package com.backend.system.service.processors.user;

import com.backend.system.beans.user.UserModifyPasswordReq;
import com.backend.system.common.CustomException;
import com.backend.system.common.RequestHeaderUserInfo;
import com.backend.system.common.RequestHolder;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.User;
import com.backend.system.util.CipherUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 用户修改密码处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.USER_MODIFY_PASSWORD)
public class UserModifyPasswordProcessor extends AbstractProcessorTemplate<UserModifyPasswordReq, Boolean> {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<UserModifyPasswordReq> context) {
        UserModifyPasswordReq req = context.getData();
        // 密码加密
        String password = req.getPassword();
        String passwordEncrypt = CipherUtil.aesPasswordEncrypt(password);

        // 获取当前用户信息
        RequestHeaderUserInfo userInfo = RequestHolder.getUserInfo();
        Long loginId = userInfo.getLoginId();
        User user = userService.getById(loginId);
        if (!Objects.equals(user.getPassword(), passwordEncrypt)) {
            throw CustomException.argsError("原密码错误");
        }

        // 新密码加密
        String newPasswordEncrypt = CipherUtil.aesPasswordEncrypt(req.getNewPassword());
        // 修改密码
        user.setPassword(newPasswordEncrypt);
        return userService.updateById(user);
    }
}
